package com.clqteam.daoimpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.clqteam.dao.TreeDao;
import com.clqteam.util.JDBCutil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 
 * @author ZHX
 *
 */
public class TreeDaoImpl implements TreeDao{

	@Override
	public int getPaIdByeId(int eId) {
		int PaId = -2;
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT s_function.paId FROM s_function");
		sql.append(" INNER JOIN s_r_f");
		sql.append(" ON s_function.fid = s_r_f.fid");
		sql.append(" INNER JOIN s_employee");
		sql.append(" ON s_employee.rid = s_r_f.rid");
		sql.append(" WHERE s_employee.eid = ?");
		Connection con = JDBCutil.getConnection();
		try {
			PreparedStatement pst = con.prepareStatement(sql.toString());
			pst.setInt(1, eId);
			ResultSet rs = pst.executeQuery();
			if(rs.next()){
				PaId = rs.getInt("paid");
			}
			JDBCutil.closeJDBC(pst, con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return PaId;
	}

	@Override
	public JSONArray getFuncJSONArrayByPaid(int paId) {
		JSONArray js = new JSONArray();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT * FROM s_function WHERE paId = ?");
		Connection con = JDBCutil.getConnection();
		try {
			PreparedStatement pst = con.prepareStatement(sql.toString());
			pst.setInt(1, paId);
			ResultSet rs = pst.executeQuery();
			while(rs.next()){
				JSONObject j = new JSONObject();
				j.put("id", rs.getInt("fId"));
				j.put("text",rs.getString("fName"));
				j.put("state", rs.getString("fState"));
				JSONObject attr = new JSONObject();
				attr.put("furl", rs.getString("fUrl"));
				j.put("attributes", attr);
				js.add(j);				
			}
			JDBCutil.closeJDBC(pst, con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
		return js;
	}

	@Override
	public JSONArray getAllFuncJSONArrayByPaid(int paId) {
		JSONArray funs = this.getFuncJSONArrayByPaid(paId);
		for (int i = 0; i < funs.size(); i++) {
			String state = funs.getJSONObject(i).getString("state");
			if("closed".equals(state)){
				int cPaId = funs.getJSONObject(i).getInt("id");
				System.out.println(cPaId);
				JSONArray children = this.getAllFuncJSONArrayByPaid(cPaId);
				funs.getJSONObject(i).put("children", children);
			}
		}		
		
		return funs;
	}



}
